import urllib.parse
import re
import base64


def _get_real_source_url(image_url):
    try:
        image_url_ = urllib.parse.parse_qs(urllib.parse.urlparse(image_url).path)['/image_search/src']
    except Exception:
        image_url_ = [image_url]
    finally:
        assert len(image_url_) == 1
        image_url = image_url_[0]
    return image_url


_translate = str.maketrans("wkv1ju2it3hs4g5rq6fp7eo8dn9cm0bla", "abcdefghijklmnopqrstuvw1234567890")


def _parse_baidu_encoded_url(url):
    if url.startswith('http'):
        return url
    url = re.sub('AzdH3F', '/', url)
    url = re.sub("_z&e3B", ".", url)
    url = re.sub('_z2C\$q', ":", url)
    url = url.translate(_translate)
    assert url.startswith('http')
    return url


def _parse_baidu_json(response_json: dict):
    response_json = response_json['data']
    result = []
    for image_info in response_json:
        if len(image_info) == 0:
            continue
        if image_info['adType'] != '0':
            continue
        thumb_url = image_info['thumbURL']
        from_url = _parse_baidu_encoded_url(image_info['fromURL'])
        obj_url = _get_real_source_url(_parse_baidu_encoded_url(image_info['objURL']))
        description = image_info['fromPageTitle']
        description = description.replace('<strong>', '')
        description = description.replace('</strong>', '')
        image_content = None
        if 'base64' in image_info and len(image_info) > 0:
            base64_image_string = image_info['base64']
            base64_pattern = 'base64,'
            base64_index = base64_image_string.find(base64_pattern)
            image_content = base64.b64decode(base64_image_string[base64_index + len(base64_pattern): ])
            if len(image_content) == 0:
                image_content = None
        result.append((thumb_url, image_content, description, from_url, obj_url))
    return result


def _get_valid_json(json_bytes: bytes):
    index = 0
    replace_indices = []
    while True:
        base64_pattern = b'"base64": \''
        base64_begin = json_bytes.find(base64_pattern, index)
        if base64_begin == -1:
            break
        replace_indices.append(base64_begin + len(base64_pattern) - 1)
        base64_begin += len(base64_pattern)
        base64_end = json_bytes.find(b'\'', base64_begin)
        if base64_end == -1:
            break
        replace_indices.append(base64_end)
        index = base64_end + 1
    if len(replace_indices) > 0:
        json_bytes = bytearray(json_bytes)
        for index in replace_indices:
            json_bytes[index: index + 1] = b'"'
        json_bytes = bytes(json_bytes)

    json_bytes = json_bytes.replace(b"\\'", b"'")
    return json_bytes
